package com.talkyun.utils.crypt;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class AesCrypt {
    private static final String ALG_NAME = "AES";
    private static final int ALG_LENGTH = 256; // 128

    public static byte[] encrypt(byte[] bytes, String key) {
        try {
            Cipher cipher = Cipher.getInstance(ALG_NAME);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(getSecretKey(key).getEncoded(), ALG_NAME));

            return cipher.doFinal(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] decrypt(byte[] bytes, String key) {
        try {
            Cipher cipher = Cipher.getInstance(ALG_NAME);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(getSecretKey(key).getEncoded(), ALG_NAME));
            return cipher.doFinal(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static SecretKey getSecretKey(String key) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        KeyGenerator gen = KeyGenerator.getInstance(ALG_NAME);
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes("utf-8"));
        gen.init(ALG_LENGTH, random);
        return gen.generateKey();
    }

}